﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSHTML;
using System.Net;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;

namespace AutoClick
{

    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }
        private List<BrowserAction> executeScript(string script)
        {
            string[] webactions = Regex.Split(script, "\r\n", RegexOptions.IgnoreCase);

           

            List<BrowserAction> result = new List<BrowserAction>();

            foreach (string obj in webactions)
            {
                string[] wa = obj.Split(',');
                //println "${id}  ${wa[0]} ${wa[1]} ${wa.size() > 2? wa[2] :''}" 
                if (wa.Length > 1)
                {
                    result.Add(new BrowserAction(
                         wa[0].Trim(),
                         wa[1].Trim(),
                         wa.Length > 2 ? wa[2].Trim() : ""
                    ));
                }
            }
            return result;
        }
        private void button1_Click(object sender, EventArgs e)
        {

            List<BrowserAction> a = new List<BrowserAction>();

            //a.Add(new BrowserAction("open", "http://www.baidu.com"));
            //a.Add(new BrowserAction("sleep", "5"));
            //a.Add(new BrowserAction("input", "id|kw", "山寨机"));
            //a.Add(new BrowserAction("sleep", "3"));
            //a.Add(new BrowserAction("click", "id|su"));
            //a.Add(new BrowserAction("sleep", "3"));
            //a.Add(new BrowserAction("click", "link|www.shanzhaiji.cn"));
            //a.Add(new BrowserAction("open", "www.shanzhaiji.cn"));
            //a.Add(new BrowserAction("sleep", "3"));
            //a.Add(new BrowserAction("iframead", "googleads.g.doubleclick.net"));
            //a.Add(new BrowserAction("sleep", "3"));

            //a.Add(new BrowserAction("open", "http://www.baidu.com"));
            //a.Add(new BrowserAction("sleep", "2"));
            //a.Add(new BrowserAction("input", "id|kw", "商铺"));
            //a.Add(new BrowserAction("sleep", "3"));
            //a.Add(new BrowserAction("click", "id|su"));
            //a.Add(new BrowserAction("sleep", "3"));
            //a.Add(new BrowserAction("clickad", "titleregex|铺铺旺"));
            //a.Add(new BrowserAction("sleep", "3"));


            //a.Add(new BrowserAction("open", "http://localhost/index/test"));
            //a.Add(new BrowserAction("sleep", "3"));
            //a.Add(new BrowserAction("clickad", "titleregex|中国"));
            //a.Add(new BrowserAction("sleep", "1"));

            //a.Add(new BrowserAction("quit", "quit"));

            a = executeScript(this.script.Text);

            BrowserPipe bp = new BrowserPipe(this);
            bp.process(a);

            logs.AppendText("\r\nOK");

        }

        private void button2_Click(object sender, EventArgs e)
        {
            string tenk = (System.DateTime.Now.Millisecond.ToString());
            this.logs.Text = tenk + "\r\n" + SendRequest("http://localhost/api/website?" + tenk);
        }

        /********************  
*C# HTTP Request请求程序模拟***  
 * 向服务器送出请求  
 * */
        public string SendRequest(string url)
        {
            HttpWebRequest request =
            (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode.ToString() != "OK")
            {
                return response.StatusDescription.ToString();
            }

            StreamReader Reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

            return Reader.ReadToEnd();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show("" + Regex.IsMatch(this.textBox1.Text, this.textBox2.Text));
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //IntPtr winHwnd = FindWindow("IEFrame", null);
            //while(winHwnd != IntPtr.Zero){
            //    //winHwnd.
            //    logs.AppendText(winHwnd.ToString());

            //    PostMessage(winHwnd, WM_CLOSE, 0,0);

            //    winHwnd = IntPtr.Zero;
            //}


            //CallBack myCallBack = new CallBack(Main.Report);
            //EnumWindows(myCallBack, 0);

            KillIEWindows();
        }

        public delegate bool CallBack(int hwnd, int lParam);

        public static bool Report(int hwnd, int lParam)
        {

            Console.Write("Window handle is :");

            Console.WriteLine(hwnd);

            return true;

        }
        public const int WM_CLOSE = 0x10;

        [DllImport("user32")]
        public static extern int EnumWindows(CallBack x, int y);

        [DllImport("user32.dll", SetLastError = true)]
        static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 关闭IE窗口
        /// </summary>
        private void KillIEWindows()
        {
            Process[] process = Process.GetProcesses();
            for (int i = 0; i < process.Length; i++)
            {
                if (process[i].ProcessName.ToLower() == "iexplore")
                {
                    try
                    {
                        process[i].Kill();
                        Thread.Sleep(500);
                    }
                    catch
                    {
                    }
                }
            }
        }

        private void Main_Load(object sender, EventArgs e)
        {

        }

    }


    public class BrowserAction
    {
        public string action = "";
        public string target = "";
        public string value = "";
        public BrowserAction(string a, string t)
        {
            action = a;
            target = t;
        }
        public BrowserAction(string a, string t, string v)
        {
            action = a;
            target = t;
            value = v;
        }
        public bool check()
        {
            if (action.Equals("") || target.Equals(""))
            {
                return false;
            }
            return true;
        }
    }
}
